<template>
	<view class="_abbr">
		<view class="public">
			<h1>整单入库</h1>
			<u-input placeholder="请扫描货位" class="put-w" v-model="wholeOrder.local" @blur="wholeOrderHouse">
				<template slot="suffix">
					<u-icon name="scan" size="30" @click="doScanLocation"></u-icon>
				</template>
			</u-input>
		</view>
		<view class="public">
			<view class="device-count">
				<view v-for="(item, index) in deviceTypeList" :key="index">
					<view class="device-item">
						<span>{{item.deviceType}}</span>
						<span>{{item.countType || 0}}/{{item.sumCountType || 0}}</span>
					</view>
				</view>
			</view>
			<u-form ref="uForm">
				<u-form-item label-width="100rpx" prop="deviceQr">
					<view class="scan-item item1">
						<input
							:focus="isFocus" 
							placeholder="扫描或输入二维码/容器码" 
							:value="deviceForm.deviceQr"
							@blur="confirm" 
							type="text" 
							class="input">
						<view class="right-icon">
							<view class="icon" @click="doScan">
								<u-icon size="30" name="scan"></u-icon>
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item label-width="100rpx" prop="location">
					<u-input placeholder="扫描或输入货位" class="put-w" v-model="locationForm.location">
						<template slot="suffix">
							<u-icon name="scan" size="30" @click="doScan1"></u-icon>
						</template>
					</u-input>
				</u-form-item>
			</u-form>
			<view class="confirm-btn" v-if="ifOnlyOne">
				<u-button type="primary" @click="confirmValue" text="确定输入"></u-button>
			</view>
			<view class="device-fit" v-if="ifOnlyOne">
				<text class="fit-name">配置信息</text>
				<view class="line"></view>
				<view class="content">
					<view class="device">
						<view class="name">
							二维码：{{deviceForm.deviceQr || ''}}
						</view>
						<view class="name">
							PO单号: {{deviceForm.workOrderId || ''}}
						</view>
						<view class="name">
							SN: {{deviceForm.deviceSn || ''}}
						</view>
						<view class="name">
							型号:{{ deviceForm.deviceType || ''}} {{ deviceForm.deviceBrand || ''}} {{deviceForm.deviceModel || ''}}
						</view>
						<view class="name">
							设备规格：{{deviceSpecsNew || ''}}
						</view>
						<view class="name">
							设备状态：{{deviceForm.deviceStatus || ''}}
						</view>
						<view class="name">
							故障信息：
							<span
								v-for="item in deviceForm.deviceFaultVos"
								:key="item.faultId"
							>
							  {{ item.faultType }}
							</span>
						</view>
					</view>
					<view v-for="item in deviceForm.deviceModelMediaVos" :key="item.mediaId">
						<u-image 
							:showLoading="true" 
							:src="item.fileUrl" 
							width="100px"
							height="100px"
							>
						</u-image>
					</view>
				</view>
			</view>
			<view v-if="!ifOnlyOne" v-for="(item, index) in containerList" :key="index" style="border: 1px solid #eee; padding: 10px;"> 
				<view>{{item.deviceType || ''}} {{item.deviceBrand || ''}} {{item.deviceModel || ''}}</view>
				<view>{{item.originalCount || ''}} {{item.unit || ''}}</view>
				<u--input v-model="item.count"  @change="validateCount(item)"></u--input>
			</view>
			<u-button v-if="!ifOnlyOne" type="primary" @click="handleContainerHouse" text="确定入库"></u-button>
			<!--选择器搜索组件-->
			<pickerSearch v-model="isLocation" :dataSource='locationList' :pickerValues="[0]" @recload='confirmLocation'></pickerSearch>
			<view class="title">一物一码入库单</view>
			<view class="line"></view>
			<u-row gutter="10" justify="space-between">
				<u-col span="3" textAlign="center" align="center">二维码</u-col>
				<u-col span="3" textAlign="center" align="center">设备型号</u-col>
				<u-col span="2" textAlign="center" align="center">数量</u-col>
				<u-col span="2" textAlign="center" align="center">货位</u-col>
				<u-col span="2" textAlign="center" align="center">操作</u-col>
			</u-row>
			<view v-for="(item, index) in dataForm" :key="index">
				<u-row gutter="10">
					<u-col span="3" textAlign="center" align="center">{{item.deviceQr}}</u-col>
					<u-col span="3" textAlign="center" align="center">{{item.deviceModel ||''}}</u-col>
					<u-col span="2" textAlign="center" align="center">{{item.count || ''}}</u-col>
					<u-col span="2" textAlign="center" align="center">{{item.location || ''}}</u-col>
					<u-col span="2" textAlign="center" align="center">
						<u-button size="medium" icon="close" :custom-style="{border:'none'}" :hair-line='false' @click="cancelHouse(item)"></u-button>
					</u-col>
				</u-row>
			</view>
			<uni-pagination :current="page.current" @change="handleCurrentChange()" :show-icon="true" :total="page.total" title="标题文字" />
			<view class="title">容器码入库单</view>
			<view class="line"></view>
			<u-row gutter="10" justify="space-between">
				<u-col span="3" textAlign="center" align="center">容器码</u-col>
				<u-col span="3" textAlign="center" align="center">设备型号</u-col>
				<u-col span="2" textAlign="center" align="center">数量</u-col>
				<u-col span="2" textAlign="center" align="center">货位</u-col>
				<u-col span="2" textAlign="center" align="center">操作</u-col>
			</u-row>
			<view v-for="(item, index) in containerQrForm" :key="index">
				<u-row gutter="10">
					<u-col span="3" textAlign="center" align="center">{{item.containerQrOld}}</u-col>
					<u-col span="3" textAlign="center" align="center">{{item.deviceModel ||''}}</u-col>
					<u-col span="2" textAlign="center" align="center">{{item.count ||''}}</u-col>
					<u-col span="2" textAlign="center" align="center">{{item.containerQr || ''}}</u-col>
					<u-col span="2" textAlign="center" align="center">
						<u-button size="medium" icon="close" :custom-style="{border:'none'}" :hair-line='false' @click="cancelContainerHouse(item)"></u-button>
					</u-col>
				</u-row>
			</view>
		</view>
		<view class="public">
			<view class="button">
				<u-button type="primary" @click="sub" text="结束入库"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request';
	import loginVue from '../../user/login.vue';
	import pickerSearch from '@/compoments/pickerSearch.vue'
	export default {
		name: 'detail',
		components: {pickerSearch},
		data() {
			return {
				containerQrForm: [], // 容器码列表
				ifOnlyOne: true,
				deviceTypeList:  [],
				deviceSpecsNew: '',
				isFocus: true, // 二维码是否聚焦
				isFocusLocation: true, //货位是否聚集
				wholeOrder: {
					local: '',
					workOrderId: ''
				}, //整单入库
				containerParams: {}, // 容器码参数
				containerList: [], //容器码查询列表
				isLocation: false,
				locationList: [],
				locationForm:{
					location: ''
				},
				deviceQr: '', //二维码
				workOrderId: '', // 工单号
				dataForm: [], // 待入库单数据
				deviceForm: {
					deviceQr: ''
				}, //设备详情数据
				subForm: {
					workOrderId: undefined,
					method : undefined,
				},
				requestParams:{
					deviceBrand: undefined,
					deviceCondition: undefined,
					deviceFlowDirection: undefined,
					deviceModel: undefined,
					deviceModelId: undefined,
					devicePn: undefined,
					deviceProperties: undefined,
					deviceSn: undefined,
					deviceSpecs: undefined,
					deviceStatus: undefined,
					deviceType: undefined,
					deviceTypeId: undefined
				},
				queryParams: {
					// pageNum: 1,
					pageSize: 10,
				},
				page: {
					total: 0,
					current: 1,
				}
			}
		},
		onLoad(options) {
			uni.showLoading({
				title:'正在加载中'
			})
			this.workOrderId = options.workId;
			this.getData();
			this.getContainerQrForm()
			this.getDeviceList()
			uni.hideLoading()
		},
		methods: {
			// 监听数量的变化
			validateCount(item) {
				if (item.count > item.originalCount) {
					uni.showToast({
						title:'输入的数量不能大于实际数量',
						icon:'none'
					})
				}
			},
			// 获取容器码列表
			getContainerQrForm() {
				request({
					url: 'system/containerOperate/list',
					method: "GET",
					data: {
						orderId: this.workOrderId,
						operatePhase:"入库",
						operate : "增加",
					}
				}).then((res) => {
					if (res.code === 200) {
						this.containerQrForm = res.rows
					}
				})
			},
			// 确定输入
			confirmValue() {
				if (!this.deviceForm.deviceQr) {
					uni.showToast({
						title:'输入或扫描二维码',
						icon:'none'
					})
					return
				}
				if (!this.locationForm.location) {
					uni.showToast({
						title:'输入或扫描货位',
						icon:'none'
					})
					return
				}
				this.getLocatinList()
			},
			// 查询货位 判断货位是否存在
			getLocatinList() {
				request({
					method: 'GET',
					url: 'system/location/list',
					data: {
						code: this.locationForm.location
					},
				}).then(res => {
					if (res.data.length === 0) {
						uni.showToast({
							title:'该货位不存在',
							icon:'none'
						})
						return
					} else {
						this.handleWareHouse()
					}
				})
			},
			// 二维码确定
			confirm(e) {
				this.isFocus = false
				if (e.detail.value) {
					this.deviceForm.deviceQr = e.detail.value
					if (e.detail.value.startsWith('CINO-C')) {
						this.ifOnlyOne = false
						this.containerParams.containerQr = e.detail.value
						this.getContainerList()
					} else {
						this.getDeviceDetail()
					}
				}
			},
			// 扫码二维码
			doScan() {
				uni.scanCode({
					success: (res) =>{
						this.deviceForm.deviceQr = res.result
						this.$forceUpdate(); // 强制更新组件
						// 判断是一物一码还是容器码
						if (this.deviceForm.deviceQr.startsWith('CINO-C')) {
							this.ifOnlyOne = false
							this.containerParams.containerQr = e.detail.value
							this.getContainerList()
						} else {
							this.getDeviceDetail()
						}
					}
				})
			},
			// 扫码货位
			doScan1() {
				uni.scanCode({
					success: (res) =>{
						this.locationForm.location = res.result
						this.$forceUpdate(); // 强制更新组件
					}
				})
			},
			// 查询容器码数据
			getContainerList() {
				request({
					url: 'system/container/list',
					method: "GET",
					data: {
						containerQr: this.containerParams.containerQr
					}
				}).then((res) => {
					if (res.code === 200) {
						this.containerList = res.rows
						this.containerList.forEach(item =>{
							item.originalCount = item.count
						})
					}
				})
			},
			// 容器码设备入库
			handleContainerHouse() {
				if (!this.locationForm.location) {
					uni.showToast({
						title:'输入或扫描货位',
						icon:'none'
					})
					return
				}
				let containerList1 = []
				containerList1 = this.containerList.map((item) => ({
				  ...item,
				  containerQrOld: item.containerQr,
				  containerQr: this.locationForm.location,
				  operatePhase: "入库",
				  operate: "增加",
				  orderId: this.workOrderId,
				  method: "io_success"
				}));
				request({
					url: 'system/containerOperate/batch',
					method: "POST",
					data: containerList1
				}).then((res) => {
					if (res.code === 200) {
						uni.showToast({
							title:'入库成功',
							icon:'none'
						})
						this.locationForm.location = ''
						this.deviceForm.deviceQr = ''
						this.containerParams.containerQr = ''
						this.getContainerQrForm()
						this.getDeviceList()
						this.reset()
					} else {
						uni.showToast({
							title: res.msg,
							icon:'none'
						})
					}
				})
			},
			// 整单入库
			wholeOrderHouse() {
				const self = this
			    uni.showModal({
			        title: '确定整单入库吗',
			        success: (res) => {
			            if (res.confirm) {
			               self.wholeOrder.workOrderId = self.workOrderId;
			                if (self.wholeOrder.local) {
			                    request({
			                        url: 'system/detail/orderLocal',
			                        method: "GET",
			                        data: self.wholeOrder
			                    }).then((res) => {
			                        if (res.code === 200) {
			                            uni.showToast({
			                                title:'整单入库成功',
			                                icon:'none'
			                            });
			                            self.wholeOrder.local = '';
										self.getData()
										self.getDeviceList()
			                        } else {
			                            uni.showToast({
			                                title: res.msg,
			                                icon:'none'
			                            });
			                            self.wholeOrder.local = '';
			                        }
			                    });
			                }
			            } else if (res.cancel) {
			                console.log('用户点击取消');
			            }
			        }
			    });
			},
			// 扫描货位码
			doScanLocation() {
				uni.scanCode({
					success: (res) =>{
						this.wholeOrder.local = res.result
						this.wholeOrderHouse()
					}
				})
			},
			reset() {
				// this.deviceForm = {};
				this.deviceForm = {
					deviceQr: ''
				}
				this.containerList = []
				this.ifOnlyOne = true
				this.deviceSpecsNew = ''
			},
			// 选择货位
			handleSelectLocation() {
				const workId = this.workOrderId
				uni.redirectTo({
					url: 'location?workId=' + workId
				})
			},
			// 确认货位
			confirmLocation(data) {
				this.locationForm.location = data.name
				this.isLocation = false
			},
			// 货位列表
			getlocationList() {
				this.isLocation = true;
				request({
					url: 'system/location/list',
					method: "GET",
				}).then((res) => {
					this.locationList = res.data.slice(9)
					this.locationList = this.locationList.map((item, index) => {
					    return {
					        id: index + 1,
					        name: item.code
					    };
					});
				})
			},
			// 扫码
			scanCode() {
				if (this.locationForm.location) {
					uni.scanCode({
						success: (res) => {
							this.deviceQr = res.result
							this.getDeviceDetail(res.result);
						}
					})
				} else {
					uni.showToast({
						title:'请先选择货位',
						icon:'none'
					})
				}
			},
			// 扫码获取设备详情
			getDeviceDetail() {
				if (this.deviceForm.deviceQr) {
					request({
						method: 'GET',
						url: `system/detail/${this.deviceForm.deviceQr}`,
					}).then(res => {
						if (res.code === 200 && res.data) {
							this.deviceForm = res.data
							if (res.data) {
								// console.log(JSON.parse(res.data.deviceSpecs))
							    const specsArray = JSON.parse(res.data.deviceSpecs);
							    this.deviceSpecsNew = specsArray.map(spec => spec[2]).join(' ');
							}
							this.requestParams = {
								deviceBrand: this.deviceForm.deviceBrand,
								deviceCondition: this.deviceForm.deviceCondition,
								deviceFlowDirection: this.deviceForm.deviceFlowDirection,
								deviceModel: this.deviceForm.deviceModel,
								deviceModelId: this.deviceForm.deviceModelId,
								devicePn: this.deviceForm.devicePn,
								deviceProperties: this.deviceForm.deviceProperties,
								deviceSn: this.deviceForm.deviceSn,
								deviceSpecs: this.deviceForm.deviceSpecs,
								deviceStatus: this.deviceForm.deviceStatus,
								deviceType: this.deviceForm.deviceType,
								deviceTypeId:this.deviceForm.deviceTypeId,
							}
							this.deviceForm.location = this.locationForm.location
							if (res.data.workOrderId !== this.workOrderId) {
								uni.showToast({
									title:"请扫描该单的设备",
									icon:'none'
								})
								return
							}
						} else {
							this.deviceForm.workOrderId = this.workOrderId
						}
					})
				} else {
					uni.showToast({
						title:"请输入或扫码二维码",
						icon:'none'
					})
				}
			},
			handleCurrentChange(val) {
				this.page.current = val.current
				this.getData()
			},
			// 获取入库数据
			getData() {
				request({
					url: "system/detail/list",
					data: {
						workOrderId: this.workOrderId,
						deviceFlowStatus: "已入库",
						pageNum: this.page.current,
						...this.queryParams
					}
				}).then(res => {
					this.dataForm = res.rows
					this.dataForm.forEach((item) =>{
						item.count = 1
					})
					this.page.total = res.total
					// this.getDeviceList()
					this.reset()
				})
			},
			getDeviceList() {
				// console.log(11)
				request({
					method: "GET",
					url: 'system/detail/statistics',
					data: {
						workOrderId: this.workOrderId,
						deviceFlowStatus:"已入库",
						operatePhase: "入库"
					}
				}).then(res => {
					this.deviceTypeList = res.rows
				})
			},
			// 一键入库
			handleWareHouse() {
				if(this.deviceForm.workOrderId !== this.workOrderId) {
					uni.showToast({
						title:"该设备不是本单的设备，不允许提交",
						icon:'none'
					})
					return
				}
				request({
					method: "GET",
					url: `system/detail/${this.deviceForm.deviceQr}`,
				}).then((res) => {
					if (res.data) {
						const self = this; // 保存当前对象的引用
						request({
							url: "system/detail",
							method: 'PUT',
							data: {
								method: "io_success",
								deviceQr: self.deviceForm.deviceQr,
								workOrderId: self.workOrderId,
								location: self.locationForm.location,
								count: 1
							}
						}).then((res) => {
							if (res.code === 200) {
								uni.showToast({
									title: "入库成功",
									icon: 'none'
								});
								self.getData();
								self.getDeviceList()
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								});
							}
						})
					} else {
						const self = this;
						uni.showModal({
							title: '该设备不存在，是否要入库',
							success: function (res) {
								if (res.confirm) {
									request({
										url: "system/detail",
										method: 'PUT',
										data: {
											method: "io_success",
											deviceQr: self.deviceForm.deviceQr,
											workOrderId: self.workOrderId,
											location: self.locationForm.location,
											count: 1
										}
									}).then((res) => {
										if (res.code === 200) {
											uni.showToast({
												title: "入库成功",
												icon: 'none'
											});
											self.getData();
											self.getDeviceList()
										} else {
											uni.showToast({
												title: res.msg,
												icon: 'none'
											});
										}
									})
								} else if (res.cancel) {
									self.reset()
								}
							}
						})
					}
				})
			},
			// 取消一物一码入库
			cancelHouse(row) {
				const self = this; // 保存当前对象的引用
				uni.showModal({
					title: '确定取消入库吗',
					success: function (res) {
						if (res.confirm) {
							request({
								url: "system/detail",
								method: 'PUT',
								data: {
									deviceQr: row.deviceQr,
									workOrderId: self.workOrderId,
									method: "cancel_io",
								}
							}).then((res) => {
								if (res.code === 200) {
									uni.showToast({
										title: "取消入库成功",
										icon: 'none'
									});
									self.getData();
									self.getDeviceList()
								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none'
									});
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			// 取消容器码入库
			cancelContainerHouse(row) {
				const self = this; // 保存当前对象的引用
				uni.showModal({
					title: '确定取消入库吗',
					success: function (res) {
						if (res.confirm) {
							request({
								url: "system/containerOperate",
								method: 'put',
								data: {
									containerQr: row.containerQr,
									operateId: row.operateId,
									containerQrOld: row.containerQrOld,
									orderId: self.workOrderId,
									method: "cancel_io",
									count: row.count,
								    unit: row.unit,
									operate: "增加",
									deviceModelId: row.deviceModelId
								}
							}).then((res) => {
								if (res.code === 200) {
									uni.showToast({
										title: "取消入库成功",
										icon: 'none'
									});
									self.getContainerQrForm();
									self.getDeviceList()
								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none'
									});
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			// 提交
			sub() {
				this.subForm.workOrderId = this.workOrderId
				this.subForm.method = "end_in_house"
				const self = this; // 保存当前对象的引用
				uni.showModal({
					title: '确定结束入库吗',
					success: function (res) {
						if (res.confirm) {
							// 提交
							request({
								url: 'system/order',
								method: "PUT",
								data: self.subForm
							}).then(res => {
								uni.reLaunch({
									url: '/pages/view/house/index'
								})
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	._abbr {
		width: 100%;
		height: 100%;
		// position: absolute;
		background-color: rgba(244, 249, 254, 1);

		.public {
			background-color: #ffffff;
			margin: 20upx;
			border-radius: 2%;
			padding: 20upx;
			border:1px solid;
			border-color:rgba(0, 124, 233, 0.4);
			.main_body_view {
				margin: 10upx;
			}
			.device-count {
				display: flex;
				margin: 10px 0;
				flex-flow: row wrap;
				align-content: flex-start;
				justify-content: flex-start;
				>view {
					box-sizing: border-box;
					flex: 0 0 33%;
					text-align: center;
				}
				.device-item {
					
					display: flex;
					flex-direction: column;
					padding:5px;
				}
			}
			.title {
				margin-top: 15px;
				font-size: 17px;
			}
			.line {
				border-bottom:1px solid #7a7378;
				margin: 3px 0 2px 0;
				width:100%;
			}
			.confirm-btn {
				padding: 24px 0 20px 0;
			}
			.device-fit {
				margin-top: 15px;
				.fit-name {
					font-size: 16px;
				}
				.line {
					border-bottom:1px solid #7a7378;
					margin: 3px 0 2px 0;
					width:100%;
				}
				.content {
					display: flex; 
					align-items: center; 
					justify-content: center;
					.device {
						// text-align: center; 
						flex: 1; 
						margin-left: 10px;
						margin: 6px 0 16px 0;
						.name {
							margin: 8px 0;
						}
					}
				}
			}
			.device-border {
				border: 1px solid #eee; 
				border-radius: 3px; 
				padding: 4px;
				margin-bottom: 6px;
			}
			.back-icon {
			    background-color: black;
			    width: 24px;
			    height: 24px;
			    border-radius: 12px;
				position: relative;
			    margin: auto;
			    .add-icon {
					position: absolute;
					top: -1px;
					left: 7px;
			        color: #ffffff;
			        font-size: 18px;
			        line-height: 24px; /* 让文本垂直居中 */
					text-align: center; /* 让文本水平居中 */
			    }
			}
			.button {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
			.main_body_view_title {
				border-bottom: 1px solid black;
				margin-bottom: 10upx;
			}
			.total-count {
				display: flex;
				align-items: center;
				justify-content: center; 
				margin-top: 10px; 
				font-size: 16px;
			}
			.scan-item {
				// margin-top: 10px;
				.input {
					margin: 10px 0 10px 6px;
					width: 100%;
				}
				.right-icon {
					position: relative;
					box-sizing: border-box;
					position: sticky;
					top: 0;
					z-index: 999;
					display: flex;
					overflow: hidden;
					justify-content: space-around;
					background: rgb(255, 255, 255);
					margin: 6px;
					.scan {
						position: absolute;
						top: 10upx;
						right:14upx;
					}
				}
				.device {
					display: flex;
					margin: 10px 0;
					justify-content: space-between;
				}
				.device-item {
					display: flex;
					align-items: center;
					flex-direction: column;
				}
				.test-scan {
					border: 1px solid #eee;
					padding: 8px;
				}
				.button {
					text-align: center; 
					margin-top: 40rpx;
					display: flex;
				}
			}
			.content {
				display: flex; 
				align-items: center; 
				justify-content: center;
				.device {
					// text-align: center; 
					flex: 1; 
					margin-left: 10px;
					font-size: 14px;
				}
			}
			.item1 {
				display: flex; 
				border: 1px solid #eee;
			}
			.user_for {
				display: flex;
			}
			.line_for {
				width: 4rpx;
				height: 24rpx;
				margin: 0 20rpx 10rpx;
			}
			.line_radio {
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				position: relative;
				left: 50%;
				transform: translateX(-50%);
				top: 0;
			}
			.right_box {
				padding: 0rpx 20rpx 20rpx 20rpx;
			}
			.desc {
				font-size: 30rpx;
				display: flex;
				margin-top: 20rpx;
				align-items: center;
			}
		}
		.write {
			display: flex;
			justify-content: space-around;
			.im {
				width: 300rpx;
				image {
					width: 200rpx;
					height: 300rpx;
					position: relative;
					left: 30rpx;
				}
			}
		}
	}
</style>